package cc.wanforme.fsync.server;

import cc.wanforme.st.server.util.AssertCheck;
import cc.wanforme.st.server.util.encryt.Base64Tool;
import cc.wanforme.st.server.vo.ResMessage;
import cc.wanforme.st.server.vo.login.LoginVo;
import cn.dev33.satoken.stp.StpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;

@RestController
@RequestMapping("/server")
public class LoginController {
    public static final Long LOGIN_ID = 1L;

    private ServerProperty serverProperty;

    /** 判断是否需要登录 */
    @PostMapping("/check")
    public ResMessage<String> checkLogin() {
        if(StringUtils.hasText(serverProperty.getUsername())
                && StringUtils.hasText(serverProperty.getPassword())) {
            StpUtil.login(LOGIN_ID); // 给一个默认登录
            return ResMessage.success(StpUtil.getTokenValue());
        }
        return ResMessage.fail(null);
    }

    @PostMapping("/login")
    public ResMessage<String> login(@RequestBody LoginVo vo) {
        String username = vo.getUsername();
        String password = vo.getPassword();

        AssertCheck.nonNull(username, "未输入用户名");
        AssertCheck.nonNull(password, "未输入密码");

        username = Base64Tool.decodeReqData(username);
        password = Base64Tool.decodeReqData(password);

        if(Objects.equals(username, serverProperty.getUsername())
            && Objects.equals(password, serverProperty.getPassword())) {
            StpUtil.login(LOGIN_ID);
            return ResMessage.success(StpUtil.getTokenValue());
        }

        return ResMessage.fail("用户名或密码错误");
    }

    @PostMapping("/logout")
    public ResMessage<Void> logout() {
        StpUtil.logout();
        return ResMessage.success();
    }

    @Autowired
    public void setServerProperty(ServerProperty serverProperty) {
        this.serverProperty = serverProperty;
    }

}
